package com.test.service;

import java.util.LinkedList;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.test.entity.Authority;
import com.test.entity.User;

@Service(value="userService")
public class UserServiceImpl implements UserService,UserDetailsService {


	@Override
	public User login(String username, String password) {
		User user = User.userByUserNameAndPassword(username, password);
		if(user!=null){
			return user;
		}
		return null;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {

		
		User u = User.findUsersByUsernameEquals(username).getSingleResult();
		u.getRolesList();
		
        List<GrantedAuthority> authorities = new LinkedList<GrantedAuthority>();
        for (Authority ur : u.getRolesList()){
        	authorities.add(ur);
        } 
		
        org.springframework.security.core.userdetails.User authUser = new org.springframework.security.core.userdetails.User(u.getUsername(), u 
        		.getPassword(), u.getEnabled(), true, true, true, authorities); 
        
        return authUser;
	}

}
